<?php

//独立的redis
function common_redis() {
    global $glob_config;
    static $redis;
    if (is_null($redis)) {
        if (!(extension_loaded('redis'))) {
            return error(-1, 'PHP 未安装 redis 扩展');
        }
        $config = $glob_config['redis'];
        if (empty($config['host'])) {
            $config['host'] = '127.0.0.1';
        }
        if (empty($config['port'])) {
            $config['port'] = '6379';
        }
        $redis_temp = new \Redis();
        if (!empty($config['persistent'])) {
            $connect = $redis_temp->pconnect($config['host'], $config['port'], $config['timeout']);
        } else {
            $connect = $redis_temp->connect($config['host'], $config['port'], $config['timeout']);
        }
        if (!($connect)) {
            throw new \Exception(-1, 'redis 连接失败, 请检查 data/config.php 中参数设置');
        }
        if (!(empty($config['password']))) {
            $redis_temp->auth($config['password']);
        }
        if (!(empty($config['select']))) {
            $redis_temp->select($config['select']);
        }
        $ping = $redis_temp->ping();
        if ($ping != '+PONG') {
            throw new \Exception(-1, 'redis 无法正常工作，请检查 redis 服务');
        }
        $redis = $redis_temp;
    }
    return $redis;
}

function random_char($length = 6, $chars = null) {
    if (empty($chars)) {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    }
    $chars = str_shuffle($chars);
    $num = $length < strlen($chars) - 1 ? $length : str_len($chars) - 1;
    return substr($chars, 0, $num);
}

//二维数组排序
function sortByMultiCols($rowset, $args) {
    $sortArray = array();
    $sortRule = '';
    foreach ($args as $sortField => $sortDir) {
        foreach ($rowset as $offset => $row) {
            $sortArray[$sortField][$offset] = $row[$sortField];
        }
        $sortRule .= '$sortArray[\'' . $sortField . '\'], ' . $sortDir . ', ';
    }
    if (empty($sortArray) || empty($sortRule)) {
        return $rowset;
    }
    eval('array_multisort(' . $sortRule . '$rowset);');
    return $rowset;
}

function write_log($data) {
    $years = date('Y-m');
    //设置路径目录信息
    $url = './log/txlog/' . $years . '/' . date('Ymd') . '_request_log';
    $dir_name = dirname($url);
    //目录不存在就创建
    if (!file_exists($dir_name)) {
        //iconv防止中文名乱码
        $res = mkdir(iconv("UTF-8", "GBK", $dir_name), 0777, true);
    }
    $fp = fopen($url, "a"); //打开文件资源通道 不存在则自动创建       
    fwrite($fp, var_export($data, true) . "\r\n"); //写入文件
    fclose($fp); //关闭资源通道
}

/*
 * 缓存操作(写)
 */

function Redis_setCache($name, $value, $expire = null) {
    $default_expire = 3600 * 24 * 7; //7天有效期
    $prefix = 'ziyuan_caches_';
    if (is_null($expire)) {
        $expire = $default_expire;
    }
    $key = $prefix . $name;
    $value = is_scalar($value) ? $value : 'think_serialize:' . serialize($value);
    if ($expire == -1) { //永久有效 
        $result = common_redis()->set($key, $value);
    } else {
        $result = common_redis()->setex($key, $expire, $value);
    }
    return $result;
}

/*
 * 缓存操作（读）
 */

function Redis_getCache($name, $default = false) {
    $prefix = 'ziyuan_caches_';
    $key = $prefix . $name;
    $value = common_redis()->get($key);
    if (is_null($value) || false === $value) {
        return $default;
    }
    try {
        $result = 0 === strpos($value, 'think_serialize:') ? unserialize(substr($value, 16)) : $value;
    } catch (\Exception $e) {
        $result = $default;
    }
    return $result;
}

/*
 * 缓存操作(删除)
 */

function Redis_rm($name) {
    $prefix = 'ziyuan_caches_';
    $key = $prefix . $name;
    $keyslists = common_redis()->keys($key);
    if($keyslists) {
        common_redis()->del($keyslists);
    }
}
